/**
 * 
 */
package com.dmagic.cms.common.query;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnore;

/**
 * initialize value, PageNo=1, PageSize=10, first=1.
 * 
 * @param <T>
 *            Page Type.
 * @author songlin.li 2012-5-30
 */
@JsonAutoDetect
public class PageUtil<T> {
	// -- common variable --//
	public static final String ASC = "asc";

	public static final String DESC = "desc";

	// -- page parameter --//
	protected int pageNo = 1;

	protected int pageSize = -1;

	protected String orderBy = null;

	protected String order = ASC;

	protected boolean autoCount = true;

	protected boolean autoReturnFirstPage = false;

	private boolean isNeedPagination = true;

	// -- return result --//
	protected List<T> result = new ArrayList<T>();

	protected List<ConditionsBean> conditions = new LinkedList<ConditionsBean>();

	protected int totalCount = -1;

	public PageUtil() {
	}

	public PageUtil(int pageSize) {
		this.pageSize = pageSize;
	}

	// --for page used --//
	/**
	 * get current page number, start with 1 and the initialize value is 1.
	 */
	public int getPageNo() {
		return pageNo;
	}

	/**
	 * set current page number.
	 */
	public void setPageNo(final int pageNo) {
		this.pageNo = pageNo;

		if (pageNo < 1) {
			this.pageNo = 1;
		}
	}

	/**
	 * return Page object and reset PageNo
	 */
	public PageUtil<T> pageNo(final int thePageNo) {
		setPageNo(thePageNo);
		return this;
	}

	/**
	 * every page size,default -1.
	 */
	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(final int pageSize) {
		this.pageSize = pageSize;
	}

	/**
	 * return Page object and reset pageSize
	 */
	public PageUtil<T> pageSize(final int thePageSize) {
		setPageSize(thePageSize);
		return this;
	}

	/**
	 * pageNo and pageSize calculate first data position, default is 1. when
	 * first data bigger than total count then return first page.
	 */
	public int getFirst() {
		int offset = ((pageNo - 1) * pageSize) + 1;
		if (isAutoReturnFirstPage()) {
			if (offset > this.getTotalCount()) {
				this.setPageNo(1);
				return 1;
			}
		}
		return offset;
	}

	public String getOrderBy() {
		return orderBy;
	}

	public void setOrderBy(final String orderBy) {
		this.orderBy = orderBy;
	}

	public PageUtil<T> orderBy(final String theOrderBy) {
		setOrderBy(theOrderBy);
		return this;
	}

	/**
	 * order by desc or asc.
	 */
	public String getOrder() {
		return order;
	}

	/**
	 * set order mode.
	 * 
	 * @param order
	 *            's value is desc or asc, when order is more than one value,
	 *            used ',' split them.
	 */
	public void setOrder(final String order) {
		String lowcaseOrder = StringUtils.lowerCase(order);

		// check order
		String[] orders = StringUtils.split(lowcaseOrder, ',');
		for (String orderStr : orders) {
			if (!StringUtils.equals(DESC, orderStr) && !StringUtils.equals(ASC, orderStr)) {
				throw new IllegalArgumentException("order:" + orderStr + " unavailable ");
			}
		}

		this.order = lowcaseOrder;
	}

	public PageUtil<T> order(final String theOrder) {
		setOrder(theOrder);
		return this;
	}

	/**
	 * generate order by
	 * 
	 * @author songlin.li
	 * @return
	 */
	@JsonIgnore
	public String getOrderByString() {
		StringBuffer orderby = new StringBuffer();
		if (isOrderBySetted()) {
			orderby.append(" order by ").append(this.orderBy).append(" ").append(this.order);
		}
		return orderby.toString();

	}

	/**
	 * add a condition
	 * 
	 * @author songlin.li
	 * @param conditionsBean
	 */
	public PageUtil<T> addCondiction(final ConditionsBean conditionsBean) {
		conditions.add(conditionsBean);
		return this;
	}

	/**
	 * whether set order by value, no default value.
	 */
	public boolean isOrderBySetted() {
		return (StringUtils.isNotBlank(orderBy) && StringUtils.isNotBlank(order));
	}

	/**
	 * get query result whether count result records,default false.
	 */
	public boolean isAutoCount() {
		return autoCount;
	}

	/**
	 * Set the query object are automatically before executing count query to
	 * obtain the total number of records .
	 */
	public void setAutoCount(final boolean autoCount) {
		this.autoCount = autoCount;
	}

	public PageUtil<T> autoCount(final boolean theAutoCount) {
		setAutoCount(theAutoCount);
		return this;
	}

	/**
	 * if autoReturnFirstPage, when first number bigger than total count
	 * number,then return to first page.
	 * 
	 * @return
	 */
	public boolean isAutoReturnFirstPage() {
		return autoReturnFirstPage;
	}

	/**
	 * @param boolean
	 */
	public void setAutoReturnFirstPage(boolean autoReturnFirstPage) {
		this.autoReturnFirstPage = autoReturnFirstPage;
	}

	public PageUtil<T> autoReturnFirstPage(final boolean autoReturnFirstPage) {
		setAutoReturnFirstPage(autoReturnFirstPage);
		return this;
	}

	// -- Access to query results function --//

	/**
	 * Get a list of records within the page.
	 */
	public List<T> getResult() {
		return result;
	}

	/**
	 * Set the list of records within the page.
	 */
	public void setResult(final List<T> result) {
		this.result = result;
	}

	/**
	 * The total number of records, default -1.
	 */
	public int getTotalCount() {
		return totalCount;
	}

	/**
	 * Set the total number of records.
	 */
	public void setTotalCount(final int totalCount) {
		this.totalCount = totalCount;
	}

	/**
	 * Total number of pages according to pageSize and totalCount terms, default
	 * -1.
	 */
	public int getTotalPages() {
		if (totalCount < 0) {
			return -1;
		}

		int count = totalCount / pageSize;
		if (totalCount % pageSize > 0) {
			count++;
		}
		return count;
	}

	/**
	 * Whether there are Next Page.
	 */
	public boolean isHasNext() {
		return (pageNo + 1 <= getTotalPages());
	}

	/**
	 * Made on the next page Page number, numbered from 1. This page is Last
	 * still returns the serial number of the Last.
	 */
	public int getNextPage() {
		if (isHasNext()) {
			return pageNo + 1;
		} else {
			return pageNo;
		}
	}

	/**
	 * Whether there are previous page.
	 */
	public boolean isHasPre() {
		return (pageNo - 1 >= 1);
	}

	/**
	 * Made on the page the page number , the serial number from 1. This page is
	 * First still returns the serial number of the First.
	 */
	public int getPrePage() {
		if (isHasPre()) {
			return pageNo - 1;
		} else {
			return pageNo;
		}
	}

	/**
	 * @return
	 */
	@JsonIgnore
	public List<ConditionsBean> getConditions() {
		return conditions;
	}

	/**
	 * @param List
	 *            <ConditionsBean>
	 */
	public void setConditions(List<ConditionsBean> conditions) {
		this.conditions = conditions;
	}

	/**
	 * @return
	 */
	public boolean isNeedPagination() {
		return isNeedPagination;
	}

	/**
	 * @param boolean
	 */
	public void setNeedPagination(boolean isNeedPagination) {
		this.isNeedPagination = isNeedPagination;
	}

}
